package fun.ironcow.test;

import com.itextpdf.awt.geom.AffineTransform;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.xslf.usermodel.*;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @author chen ming
 * @date 2023/12/3 23:18
 */

public class TestPdf {
    /**
     * 将ppt转为pdf，兼容ppt和pptx
     * @param is
     * @return
     */
    public static byte[] ppt2pdf(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] resBytes = null;
        try {
            Document pdfDocument = new Document();
            PdfWriter pdfWriter = PdfWriter.getInstance(pdfDocument, baos);
            HSLFSlideShow hslfSlideShow = new HSLFSlideShow(is);
            double zoom = 2;
            if (hslfSlideShow == null) {
                XMLSlideShow ppt = new XMLSlideShow(is);
                if (ppt == null) {
                    throw new NullPointerException("获取ppt文件数据失败");
                }
                Dimension pgsize = ppt.getPageSize();
                java.util.List<XSLFSlide> slide = ppt.getSlides();
                java.awt.geom.AffineTransform at = new java.awt.geom.AffineTransform();
                at.setToScale(zoom, zoom);
                pdfDocument.setPageSize(new com.itextpdf.text.Rectangle((float) Math.ceil(pgsize.width * zoom), (float) Math.ceil(pgsize.height * zoom)));
                pdfWriter.open();
                pdfDocument.open();
                PdfPTable table = new PdfPTable(1);
                for (XSLFSlide xslfSlide : slide) {
                    BufferedImage img = new BufferedImage((int) Math.ceil(pgsize.width * zoom), (int) Math.ceil(pgsize.height * zoom), BufferedImage.TYPE_INT_RGB);
                    Graphics2D graphics = img.createGraphics();
                    graphics.setTransform(at);

                    graphics.setPaint(Color.white);
//                    graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                    graphics.fill(new java.awt.geom.Rectangle2D.Float(0, 0, pgsize.width*2, pgsize.height*2));
                    xslfSlide.draw(graphics);
                    graphics.getPaint();
                    com.itextpdf.text.Image slideImage = com.itextpdf.text.Image.getInstance(img, null);
                    table.addCell(new PdfPCell(slideImage, true));
                }
                ppt.close();
                pdfDocument.add(table);
                pdfDocument.close();
                pdfWriter.close();
                resBytes = baos.toByteArray();
                return resBytes;
            }
            Dimension pgsize = hslfSlideShow.getPageSize();
            java.util.List<HSLFSlide> slides = hslfSlideShow.getSlides();
            pdfDocument.setPageSize(new com.itextpdf.text.Rectangle((float)  Math.ceil(pgsize.width * zoom), (float) Math.ceil(pgsize.height * zoom)));
            pdfWriter.open();
            pdfDocument.open();
            java.awt.geom.AffineTransform at = new java.awt.geom.AffineTransform();
            PdfPTable table = new PdfPTable(1);
            for (HSLFSlide hslfSlide : slides) {
                BufferedImage img = new BufferedImage((int) Math.ceil(pgsize.width * zoom), (int) Math.ceil(pgsize.height * zoom), BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setTransform(at);

                graphics.setPaint(Color.white);
                graphics.fill(new java.awt.geom.Rectangle2D.Float(0, 0, pgsize.width*2, pgsize.height*2));
                hslfSlide.draw(graphics);
                graphics.getPaint();
                com.itextpdf.text.Image slideImage = com.itextpdf.text.Image.getInstance(img, null);
                table.addCell(new PdfPCell(slideImage, true));
            }
            hslfSlideShow.close();
            pdfDocument.add(table);
            pdfDocument.close();
            pdfWriter.close();
            resBytes = baos.toByteArray();
            return resBytes;
        } catch (Exception e) {
            e.printStackTrace();
//            log.error("ppt转为pdf异常：{}",e);
        }
        return resBytes;
    }

    public static byte[] pptxToPdf(InputStream src) {
        Document document = null;
        XMLSlideShow slideShow = null;
        FileOutputStream fileOutputStream = null;
        PdfWriter pdfWriter = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] resBytes = null;
        try {
            //使用输入流pptx文件
            slideShow = new XMLSlideShow(src);
            //获取幻灯片的尺寸
            Dimension dimension = slideShow.getPageSize();
            //创建一个写内容的容器
            document = new Document(PageSize.A3, 72, 72, 72, 72);
            //使用输出流写入
            pdfWriter = PdfWriter.getInstance(document, baos);
            //使用之前必须打开
            document.open();
            pdfWriter.open();
            PdfPTable pdfPTable = new PdfPTable(1);
            //获取幻灯片
            java.util.List<XSLFSlide> slideList = slideShow.getSlides();
            for (int i = 0, row = slideList.size(); i < row; i++) {
                //获取每一页幻灯片
                XSLFSlide slide = slideList.get(i);
                for (XSLFShape shape : slide.getShapes()) {
                    //判断是否是文本
                    if(shape instanceof XSLFTextShape){
                        // 设置字体, 解决中文乱码
                        XSLFTextShape textShape = (XSLFTextShape) shape;
                        for (XSLFTextParagraph textParagraph : textShape.getTextParagraphs()) {
                            for (XSLFTextRun textRun : textParagraph.getTextRuns()) {
                                textRun.setFontFamily("宋体");
                            }
                        }
                    }
                }
                //根据幻灯片尺寸创建图形对象
                BufferedImage bufferedImage = new BufferedImage((int)dimension.getWidth(), (int)dimension.getHeight(), BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics2d = bufferedImage.createGraphics();
                graphics2d.setPaint(Color.white);
                graphics2d.setFont(new java.awt.Font("宋体", java.awt.Font.PLAIN, 12));
                //把内容写入图形对象
                slide.draw(graphics2d);
                graphics2d.dispose();
                //封装到Image对象中
                com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(bufferedImage, null);
                image.scalePercent(50f);
                // 写入单元格
                pdfPTable.addCell(new PdfPCell(image, true));
                document.add(image);
            }
            document.close();
            pdfWriter.close();
            resBytes = baos.toByteArray();
        } catch (Exception e) {
//            log.error("pptx转pdf异常：{}",e);
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException e) {
//                log.error("pptx转pdf关闭io流异常：{}",e);
            }
        }
        return resBytes;
    }



    public static void main(String[] args) throws IOException {
        FileInputStream inputStream = new FileInputStream("C:\\Users\\86166\\Pictures\\pdf\\测试pptx.pptx");
        byte[] bytes = pptxToPdf(inputStream);
//        byte[] bytes = ppt2pdf(inputStream);
        FileOutputStream outputStream = new FileOutputStream("C:\\Users\\86166\\Pictures\\pdf\\测试pptx.pdf");
        outputStream.write(bytes);
//调用第三方插件形式：https://github.com/microacup/office2pdf
//能用但是需要调整 现已知问题：pptx拿不到表格和图标 word拿不到删除线 表格需要按照格式做才行 生成有很多细节都有问题
//https://github.com/yeokm1/docs-to-pdf-converter

        //参考文档  解决pptx读取不到问题
        //https://blog.csdn.net/xuwenze/article/details/125292466
    }



}
